<?php
/**
 * 
 * @author jacky
 *
 */
class PrescriptionController extends Controller {
	
	/**
	 * Method returning filters array.
	 */
	public function filters()
	{
		return array(
				'accessControl',//Performs access control for CRUD operations
		);
	}
	
	/**
	 * Defines User Access Level.
	 */
	public function accessRules()
	{
		return array(
				array('allow',
						'actions'=>array(),//Actions allowed
						'roles'=>array('@'),//Roles allowed to perform actions
				),
				array('deny',
						'actions'=>array(),//Actions not allowed
						'roles'=>array('*'),//Roles not allowed to perform actions
				),
		);
	}
	
	/**
	 * Declares class-based actions.
	 */
	public function actions(){
		return array(
				// captcha action renders the CAPTCHA image displayed on the contact page
				'captcha'=>array(
						'class'=>'CCaptchaAction',
						'height'=>37,
						'minLength'=>4,
						'maxLength'=>6,
						'backColor'=>0xFFFFFF,
				),
				// page action renders "static" pages stored under 'protected/views/site/pages'
				// They can be accessed via: index.php?r=site/page&view=FileName
				'page'=>array(
						'class'=>'CViewAction',
				),
		);
	}

    /******************************************************************************************
     * Functions in Patient Prescription
     ******************************************************************************************/

    /**
     * Get Patient Prescription
     * @param bigint $pk_outpatient_id
     */
    public function actionGetPatientPrescription($pk_outpatient_id){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $patientInformation = TblOutpatients::model()->findByAttributes(array('pk_outpatient_id'=>$pk_outpatient_id));

            

            $this->layout='main';
            $this->render('patientprescription',array('pk_outpatient_id'=>$pk_outpatient_id,'patientInformation'=>$patientInformation));
        }
        else
            $this->redirect(array('site/login'));//View redirection
    }


    /**
     * Add Patient Prescription
     * @param bigint $pk_outpatient_id
     */
    public function actionAddPatientPrescription($pk_outpatient_id){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {

        	$outpatient = TblOutpatients::model()->findByAttributes(array('pk_outpatient_id'=>$pk_outpatient_id));
        	$outpatientLocation = TblOutpatientLocations::model()->findByAttributes(array('pk_fk_outpatient_id'=>$pk_outpatient_id));
        	//$pk_doctor_id = Yii::app()->session['id'];



            $this->layout='main';
            $this->render('addpatientprescription',array('pk_outpatient_id'=>$pk_outpatient_id,'outpatient'=>$outpatient,'outpatientLocation'=>$outpatientLocation));
        }
        else
            $this->redirect(array('site/login'));//View redirection
    }

    private function getAutoID(){
        $id = curl_init();
        curl_setopt($id, CURLOPT_HEADER, 0);
        curl_setopt($id, CURLOPT_VERBOSE, 0);
        curl_setopt($id, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($id, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
        curl_setopt($id, CURLOPT_POST, true);
        curl_setopt($id, CURLOPT_URL, 'http://120.24.170.79:8080/push_call_server/get-id.do?accessToken=25da2c6fc3b8e5cfcd460b3367f7788e&logicid=8');
        $responseID = curl_exec($id);
        $result = json_decode($responseID,true);
        if($result['code']==0){
            return $result['content']['id'];
        }
    }

    public function actionSavePatientPrescription($pk_outpatient_id){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
        	$result = array('status'=>0,'result'=>0);

        	$prescriptions = new TblOutpatientPrescriptions();

        	$prescriptions->attributes =array('diagnosis'=>$_POST['diagnosis'],'exhort'=>$_POST['exhort'],'medicine'=>$_POST['medicine'],'fk_doctor_id'=>Yii::app()->session['id'],'fk_outpatient_id'=>$pk_outpatient_id,'create_time'=>date('Y-m-d H:s:i',time()),'update_time'=>date('Y-m-d H:s:i',time()));
        	$prescriptions->pk_outpatient_prescription_id = $this->getAutoID();
            if($prescriptions->save()){

            // $log = new Log600100(); //Create new empty record
            // $log->action = 'save_prescription';//Saving the action type
            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
            // $log->target = $prescriptions->pk_outpatient_prescription_id;//针对对象
            // $log->save(false);//Saving the entire record with validation

                $result['result'] = $prescriptions->pk_outpatient_prescription_id;
            }else{
                $result['status'] = 1;
                $result['result'] = json_encode($prescriptions->getErrors());
            }

            echo json_encode($result);


            //$this->layout='main';
            //$this->render('addpatientprescriptioncontent',array('pk_outpatient_id'=>$pk_outpatient_id));

        }
        else
            $this->redirect(array('site/login'));//View redirection
    }

    public function actionFindPerscription($pk_outpatient_prescription_id,$pk_outpatient_id){
    	if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {

        	$outpatient = TblOutpatients::model()->findByAttributes(array('pk_outpatient_id'=>$pk_outpatient_id));
        	//$pk_doctor_id = Yii::app()->session['id'];

        	$outpatientLocation = TblOutpatientLocations::model()->findByAttributes(array('pk_fk_outpatient_id'=>$pk_outpatient_id));

        	$prescriptions = TblOutpatientPrescriptions::model()->findByAttributes(array('pk_outpatient_prescription_id'=>$pk_outpatient_prescription_id));

        	// $log = new Log600100(); //Create new empty record
         //    $log->action = 'find_prescription';//Saving the action type
         //    $log->create_time = new CDbExpression('NOW()');//Saving date and time
         //    $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
         //    $log->fk_user_id = Yii::app()->session['id'];//Saving user id
         //    $log->target = $pk_outpatient_prescription_id;//针对对象
         //    $log->save(false);//Saving the entire record with validation



            $this->layout='main';
            $this->render('patientprescriptioncontent',array('prescriptions'=>$prescriptions,'outpatient'=>$outpatient,'pk_outpatient_prescription_id'=>$pk_outpatient_prescription_id,'pk_outpatient_id'=>$pk_outpatient_id,'outpatientLocation'=>$outpatientLocation));
        }
        else
            $this->redirect(array('site/login'));//View redirection
    }

    public function actionDelprescription(){
    	$result = array('status'=>0,'result'=>0);
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {

            $prescription = TblOutpatientPrescriptions::model();
            $data['del_reason'] = $_POST['del_reason'];
            $data['invalid_time'] = date('Y-m-d h:i:s');
            $data['invalid'] = 2;
            if(!$prescription->updateByPk($_POST['pk_outpatient_prescription_id'],$data)){
                $result['status'] = 1;
                $result['result'] = json_encode($prescription->getErrors());
            }else{
            	// $log = new Log600100(); //Create new empty record
	            // $log->action = 'del_prescription';//Saving the action type
	            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
	            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
	            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
	            // $log->target = $_POST['pk_outpatient_prescription_id'];//针对对象
	            // $log->save(false);//Saving the entire record with validation
            }
        }
        else
            $result = array('status'=>2,'result'=>0);
        echo json_encode($result);
    }
	
	/**
	 * Get all outpatinet EHR
	 * @param bigint $pk_outpatient_id
	 */
	public function actionGetPerscriptionHistory($pk_outpatient_id){
		$doctor_id = Yii::app()->session['id'];
		$sql = "SELECT pk_outpatient_prescription_id,invalid,create_time FROM tbl_outpatient_prescriptions WHERE fk_outpatient_id='{$pk_outpatient_id}' AND fk_doctor_id='{$doctor_id}' ORDER BY create_time DESC";
		$outPatients = Yii::app()->db->createCommand($sql)->queryAll();
		$list = array();
		foreach($outPatients as $row){
	
			$create_time = strtotime ($row['create_time']);
			$year = date('Y',$create_time);
			$month = date('m',$create_time);
			if(!isset($list[$year])){
				$list[$year] = array('id'=>$year,'date'=>$year.'年','children'=>array());
			}
	
			if(!isset($list[$year]['children'][$month])){
				$list[$year]['children'][$month] = array('id'=>date('Y-m',$create_time),'date'=>$month.'月','children'=>array());
			}
			$day = date('d',$create_time);
			if(!isset($list[$year]['children'][$month]['children'][$day])){
				$list[$year]['children'][$month]['children'][$day] = array();
			}
			$list[$year]['children'][$month]['children'][$day][] = $row; //每一天多条
		}// end foreach
		Yii::log(json_encode($list),CLogger::LEVEL_ERROR);
		$result = array();
		foreach ($list as $rs) {
			$monthChils = array();
			foreach ($rs['children'] as $monthNum=>$month){
				$children = array();
				
				foreach ($month['children'] as $dayNum=>$day){
	
					if(count($day)>1){
						//一天有多条记录
							
						$dayRs = array('id'=>$year.$monthNum.$dayNum,'date'=>$monthNum.'月'.$dayNum,'children'=>array());
						foreach ($day as $row){
							$create_time = strtotime($row['create_time']);
							$dayRs['children'][] = array('id'=>$row['pk_outpatient_prescription_id'],'pre_id'=>$row['pk_outpatient_prescription_id'],
									'date'=>date('h点i分',$create_time),'iconCls'=>$row['invalid']==1?'icon-ok':'icon-cancel');
						}
						if(!empty($dayRs['children'])) $monthChils[] = $dayRs;
					}else{
						//一天只有一条记录
						//     					Yii::log(json_encode($day[0]),CLogger::LEVEL_ERROR);
						$create_time = strtotime($day[0]['create_time']);
						$dayRs = array('id'=>date('Ymd',$create_time),'pre_id'=>$day[0]['pk_outpatient_prescription_id'],
								'date'=>date('m月d日',$create_time),'iconCls'=>$day[0]['invalid']==1?'icon-ok':'icon-cancel');
						$monthChils[] = $dayRs;
					}// end if
					if(!empty($monthChils)) 	$month['children'] = $monthChils;
				}// end foreach ($month['children'] as $day){
				if(!empty($monthChils))   			$children[] = $month;
			}// end foreach ($rs['children'] as $month){
			$rs['children'] = $children;
			if(!empty($children))   		$result[] = $rs;
		}// end foreach ($list as $rs) {

		// $log = new Log600100(); //Create new empty record
  //       $log->action = 'list_prescription';//Saving the action type
  //       $log->create_time = new CDbExpression('NOW()');//Saving date and time
  //       $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
  //       $log->fk_user_id = Yii::app()->session['id'];//Saving user id
  //       $log->target = $pk_outpatient_id;//针对对象
  //       $log->save(false);//Saving the entire record with validation
		echo  json_encode($result);
	}
}